import random
import pyecharts.options as op
from pyecharts.charts import Radar

def generate_radar_chart(output_path='/static/charts/radar_chart.html'):
    """
    生成一个随机的雷达图，并保存为 HTML 文件。
    每次调用时，都会生成随机数据，且数值保留一位小数。
    """
    # 随机生成数据，数值在0到5之间，保留一位小数
    def generate_random_data():
        return [round(random.uniform(0, 5), 1) for _ in range(6)]

    # 创建随机数据
    v1 = [generate_random_data()]
    v2 = [generate_random_data()]
    v3 = [generate_random_data()]
    v4 = [generate_random_data()]
    v5 = [generate_random_data()]

    # 设置雷达图维度
    x_schema = [
        {"name": "价格", "max": 5, "min": 0, "color": 'white', "font_size": 18},
        {"name": "过户次数", "max": 5, "min": 0, "color": 'white', "font_size": 18},
        {"name": "驱动方式", "max": 5, "min": 0, "color": 'white', "font_size": 18},
        {"name": "排量", "max": 5, "min": 0, "color": 'white', "font_size": 18},
        {"name": "马力值", "max": 5, "min": 0, "color": 'white', "font_size": 18},
        {"name": "表显里程", "max": 5, "min": 0, "color": 'white', "font_size": 18}
    ]

    # 创建雷达图对象
    radar = Radar()
    radar.add_schema(x_schema)
    
    # 添加不同类型的车的数据
    radar.add('家用车', v1, color='red').set_colors(['red'])
    radar.add('SUV', v2, color='green').set_colors(['green'])
    radar.add('电车', v3, color='orange').set_colors(['orange'])
    radar.add('跑车', v4, color='blue').set_colors(['blue'])
    radar.add('面包车', v5, color='purple').set_colors(['purple'])

    # 设置全局选项
    radar.set_global_opts(
        title_opts=op.TitleOpts(title="车辆雷达图", pos_right="center"),
        legend_opts=op.LegendOpts(legend_icon="roundRect", align="left", pos_left='7%',
                                  pos_bottom='14%', orient='vertical')
    )

    # 渲染图表并保存为 HTML 文件
    radar.render('C:\\Users\\29741\\Desktop\\goods\\static\\charts\\radar_chart.html')
    print(f"✅ 图像已保存至 {output_path}")